package com.example.hospital.physicalExamination.service.serviceImpl;


import com.example.hospital.physicalExamination.entity.PeItems;
import com.example.hospital.physicalExamination.repository.PeItemsRepository;
import com.example.hospital.physicalExamination.service.PeItemsService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class PeItemsServiceImpl implements PeItemsService {

    @Autowired
    PeItemsRepository peItemsRepository;

    @Override
    public PeItems findPeItemsById(Long id) {
        return peItemsRepository.findPeItemsById(id);
    }

    @Override
    public Page<PeItems> findItems(Integer page, Integer size, String userId) {
        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "id");
        Page<PeItems> peItems =  peItemsRepository.findAll(new Specification<PeItems>() {
            @Override
            public Predicate toPredicate(Root<PeItems> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if(null != userId&&!"".equals(userId)){
                    list.add(criteriaBuilder.equal(root.get("userId").as(String.class), userId+""));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        },pageable);
        return peItems;
    }


    @Override
    public List<PeItems> findPeItemsByUserId(String userId) {
        return peItemsRepository.findPeItemsByUserId(userId);
    }

    @Override
    public PeItems save(PeItems peItems) {
        return peItemsRepository.save(peItems);
    }

    @Override
    public void delete(Long id) {
        peItemsRepository.deleteById(id);
    }

    @Override
    public PeItems edit(PeItems peItems) {
        return peItemsRepository.save(peItems);
    }
}
